#!groovy

@Library('jenkinslib@master') _

def dingmes  = new org.devops.ding()
def tools = new org.devops.tools()
//公共参数
def public_cmd = new org.devops.before_config.publics()
//代码作者
def Author = ''
//更新记录(3条)
def ChangeLog = ''
//gitlab仓库地址
String srcUrl = "${env.srcUrl}"
srcUrl = srcUrl.split("\\(")[0].trim()
//仓库分支
String branchName = "${env.branchName}"
//项目名称
String proJectname = "${env.project}"
//switchs name
String switchs = "${env.switchs}"
//ssh ip
String host = "${env.host}"
//ssh 端口
int port = "${env.port.trim()}"
//ssh pass
String sshpass = "${env.sshpass}"
//git pass
String gitpass = "${env.gitpass}"
//base url
String baseurl = "${env.baseurl}"
//base url
String appname = "${env.appname}"
//git回滚
String git_sha = "${env.git_sha}"
//build cmd
String build_cmd = "${env.build_cmd}"
//pipeline
pipeline{
    agent any    
    stages{

       stage("拉取代码"){
            steps{
                script{
                        workdir = srcUrl.split('/')[-1].split('.git')[0]
                        if(!workdir) {
                            println "获取工作目录失败"
                            exit()
                        }
                        tools.PrintMes("Clone代码","green")
                        checkout([$class: 'GitSCM', branches: [[name: "${branchName}"]], 
                        doGenerateSubmoduleConfigurations: false, 
                        extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "${workdir}"]], 
                        submoduleCfg: [], 
                        userRemoteConfigs: [[credentialsId: "${gitpass}", url: "${srcUrl}"]]])
                        //git id checkout
                        if(git_sha != "null" && git_sha != ""){
                            //切换git id
                            tools.PrintMes("开始执行回滚操作....","green")
                            tmp_shell="""
                                cd ${workdir}
                                git checkout -f ${git_sha}
                            """
                            sh returnStdout: true ,script: "${tmp_shell}"
                        }
                        //代码作者
                        res = sh returnStdout: true ,script: "cd ${workdir} && git log -1|grep Author |awk '{print \$2}'"
                        Author = res.trim()
                        //更新记录(5条)
                        tmp_shell="""
                            cd ${workdir}
                            git log -3 |awk '!/^\$/' |awk '/^Author|^commit/ {next}{printf "%s\\n",\$0}'
                        """
                        res = sh returnStdout: true ,script: "${tmp_shell}"
                        ChangeLog = res.trim()
                }
            }
        }
        stage("编译打包"){
            steps{
                script{
                        tools.PrintMes("执行npm编译","green")
                        //清除已有dist文件
                        sh "cd ${workdir} && rm -rf dist"
                        sh "cd ${workdir} && rm -rf dist.tar.gz"
                        //编译
                        //修改前端环境变量
                        cmds = public_cmd.switchs("${switchs}",appname,baseurl,workdir)
                        sh returnStdout: true ,script: "${cmds[0]}"
                        //打包
                        sh "cd ${workdir} && tar zcf dist.tar.gz dist"
                    }
                }
            }
       //部署
       stage('SSH') {
            steps {
                script {                 
  	                def remote = [:]
  	                remote.name = "${switchs}_web"
  	                remote.host = "${host}"
                    remote.port = port
                    remote.allowAnyHosts = true
                    withCredentials([usernamePassword(credentialsId: "${sshpass}", passwordVariable: 'password', usernameVariable: 'username')]) {
                        remote.user = "${username}"
                        remote.password = "${password}"
                    }
                    cmds = public_cmd.switchs("${switchs}",appname,baseurl,workdir)
                    //删除旧数据
                    sshCommand remote: remote, command: "${cmds[2]}"
                    //传输代码压缩包
                    //res = sh returnStdout: true ,script: "scp -o ProxyCommand='ncat --proxy-type http --proxy 61.143.60.85:8089 %h %p --proxy-auth aizhixin:Aizhixin@2021' ${workdir}/dist.tar.gz root@172.16.23.49:/aizhixin/frontend/wisdom/tar"
                    sshPut remote: remote, from: "${workdir}/dist.tar.gz", into: "${cmds[3]}"
                    //部署
                    sshCommand remote: remote, command: "${cmds[1]}"
                    //检查前端服务状态码
                    //sshCommand remote: remote, command: "curl -o /dev/null -s -w %{http_code} 127.0.0.1:8085"
                }
            }
       }
        //部署检测
        stage("deploy_check"){
            steps{
                script{
                    tools.PrintMes("检测服务状态","green")
                      //deployment status
                }
            }
        }
    }
        post{
            success{
                script{
                    tools.PrintMes("========pipeline executed successfully========",'green')
                    dingmes.HttpReq("1",branchName,"构建成功 ✅ ",Author,ChangeLog,JOB_NAME)
                }
            }
            failure{
                script{
                    tools.PrintMes("========pipeline execution failed========",'red')
                    dingmes.HttpReq("1",branchName,"构建失败 ❌",Author,ChangeLog,JOB_NAME,"请查看控制台")
                }
            }
            unstable{
                script{
                    tools.PrintMes("========pipeline execution unstable========",'red')
                    dingmes.HttpReq("1",branchName,"构建失败 ❌",Author,ChangeLog,JOB_NAME,"不稳定异常")
                }
            }
            aborted{
                script{
                    tools.PrintMes("========pipeline execution aborted========",'blue')
                    dingmes.HttpReq("1",branchName,"构建失败 ❌",Author,ChangeLog,JOB_NAME,"暂停或中断")
                }
            
        }
    }
}